package edu.ptu.springboot04.config;

import edu.ptu.springboot04.filer.AuthJwtUtilFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @BelongsProject: springboot04
 * @BelongsPackage: edu.ptu.springboot04.config
 * @Author: HYJ
 * @CreateTime: 2025-03-27  19:48
 * @Description: Spring Security 核心配置类
 * 1. 配置密码加密策略
 * 2. 设置接口访问权限
 * 3. 配置认证管理器
 * @Version: 1.0
 */
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private AuthJwtUtilFilter authJwtUtilFilter;

    /**
     * 配置密码加密器
     *
     * @return BCrypt强哈希加密器（Spring Security推荐方案）
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置HTTP安全策略
     *
     * @param http HTTP安全对象
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable()  // 禁用CSRF（适用于无状态API）
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话
//                .and().authorizeRequests()
//                .antMatchers("/user/login").permitAll()  // 登录接口匿名访问
//                .anyRequest().authenticated();  // 其他接口需要认证
        http
                .addFilterBefore(authJwtUtilFilter, UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 暴露认证管理器Bean（用于自定义认证流程）
     *
     * @return 认证管理器对象
     */
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}
